// 在文件开头添加环境变量
self.isBrowser = true;
self.isNode = false;

// 导入环境设置
importScripts('face-api-env.js');
importScripts('jszip.min.js');

// 在加载 face-api.js 之前确保环境已设置
if (!self.getEnv) {
  console.error('Environment not properly set up');
}

// 加载 face-api.js
importScripts('lib/face-api.min.js');

// 监听扩展图标点击事件
chrome.action.onClicked.addListener((tab) => {
  if (tab.url && tab.url.includes('weibo.com')) {
    chrome.tabs.sendMessage(tab.id, { action: 'toggleButtons' }).catch(() => {
      chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ['content.js']
      }).then(() => {
        chrome.tabs.sendMessage(tab.id, { action: 'toggleButtons' });
      }).catch(err => {
        console.error('Script injection failed:', err);
      });
    });
  }
});

// 存储下载任务状态
const downloadTasks = new Map();

let modelLoaded = false;

// 监听下载请求
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'startBatchDownload') {
    const taskId = Date.now().toString();
    const { downloads, csv } = request;
    
    // 初始化下载任务
    downloadTasks.set(taskId, {
      total: downloads.length,
      current: 0,
      files: [],
      tabId: sender.tab.id
    });

    // 立即响应，表示任务已创建
    sendResponse({ success: true, taskId });

    // 在后台开始处理下载
    (async () => {
      try {
        const zip = new JSZip();
        
        // 添加 CSV 文件
        if (csv) {
          zip.file('image_list.csv', csv);
        }

        // 创建 images 文件夹
        const imgFolder = zip.folder('images');
        const task = downloadTasks.get(taskId);

        // 分批下载图片
        for (const item of downloads) {
          try {
            const response = await fetch(item.url, {
              credentials: 'include',
              headers: {
                'Referer': 'https://weibo.com/'
              }
            });

            if (!response.ok) {
              throw new Error(`Failed to download image: ${response.statusText}`);
            }

            const blob = await response.blob();
            imgFolder.file(item.filename, blob);
            
            // 更新进度
            task.current++;
            task.files.push(item.filename);

            // 通知内容脚本进度更新
            chrome.tabs.sendMessage(task.tabId, {
              action: 'downloadProgress',
              taskId,
              progress: task.current / task.total,
              filename: item.filename
            }).catch(console.error);

          } catch (error) {
            console.error('Download failed for:', item.filename, error);
          }
        }

        // 生成 zip 文件
        const zipBlob = await zip.generateAsync({ type: 'blob' });

        // 将 Blob 转换为 base64
        const reader = new FileReader();
        reader.readAsDataURL(zipBlob);
        reader.onload = () => {
          const base64data = reader.result;
          
          // 使用 data URL 下载
          chrome.downloads.download({
            url: base64data,
            filename: `weibo_album_${taskId}.zip`,
            saveAs: true
          }, (downloadId) => {
            if (chrome.runtime.lastError) {
              console.error('Download failed:', chrome.runtime.lastError);
              chrome.tabs.sendMessage(task.tabId, {
                action: 'downloadError',
                taskId,
                error: chrome.runtime.lastError.message
              }).catch(console.error);
            } else {
              // 通知下载完成
              chrome.tabs.sendMessage(task.tabId, {
                action: 'downloadComplete',
                taskId
              }).catch(console.error);
            }
          });
        };

        reader.onerror = (error) => {
          throw new Error('Failed to convert zip to base64: ' + error);
        };

      } catch (error) {
        console.error('Download process failed:', error);
        chrome.tabs.sendMessage(task.tabId, {
          action: 'downloadError',
          taskId,
          error: error.message
        }).catch(console.error);
      } finally {
        // 清理任务状态
        downloadTasks.delete(taskId);
      }
    })();

    return false; // 不需要保持消息通道开放
  }

  if (request.action === 'getDownloadProgress') {
    const task = downloadTasks.get(request.taskId);
    if (task) {
      sendResponse({
        success: true,
        progress: task.current / task.total,
        completed: task.current === task.total,
        files: task.files
      });
    } else {
      sendResponse({ success: false, error: 'Task not found' });
    }
    return false;
  }

  if (request.type === 'detectFaces') {
    detectFaces(request.imageUrl, request.imageId)
      .then(result => sendResponse(result))
      .catch(error => sendResponse({ error: error.message }));
    return true;
  }
});

async function detectFaces(imageUrl, imageId) {
  try {
    if (!modelLoaded) {
      console.log('开始加载模型...');
      const modelPath = chrome.runtime.getURL('models');
      
      // 加载模型
      await faceapi.nets.ssdMobilenetv1.loadFromUri(modelPath);
      console.log('模型加载完成');
      
      modelLoaded = true;
    }

    console.log('开始检测图片:', imageUrl);
    
    // 加载图片
    const response = await fetch(imageUrl);
    const blob = await response.blob();
    const bitmap = await createImageBitmap(blob);
    
    // 创建离屏画布
    const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
    const ctx = canvas.getContext('2d');
    ctx.drawImage(bitmap, 0, 0);
    
    console.log('图片加载完成，尺寸:', bitmap.width, 'x', bitmap.height);

    // 进行人脸检测
    const detections = await faceapi.detectAllFaces(
      canvas,
      new faceapi.SsdMobilenetv1Options({
        minConfidence: 0.1,
        maxResults: 100
      })
    );

    console.log('检测结果:', detections);

    // 验证检测结果
    const validFaces = detections.filter(detection => {
      const { width, height } = detection.box;
      const faceArea = width * height;
      const imageArea = bitmap.width * bitmap.height;
      const faceRatio = faceArea / imageArea;
      
      console.log('人脸区域比例:', faceRatio, '置信度:', detection.score);
      
      return detection.score > 0.1;
    });

    // 释放资源
    bitmap.close();

    console.log('有效人脸数量:', validFaces.length);

    return {
      success: true,
      imageId,
      hasOneFace: validFaces.length === 1,
      faceCount: validFaces.length,
      confidence: validFaces.length > 0 ? validFaces[0].score : 0
    };
  } catch (error) {
    console.error('人脸检测错误:', error);
    console.error('错误堆栈:', error.stack);
    return {
      success: false,
      imageId,
      error: error.message
    };
  }
} 